package com.joinway.framework.support.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joinway.framework.bean.security.annotation.Security;
import com.joinway.framework.bean.security.type.CheckPoint;
import com.joinway.framework.core.utils.AopHelper;
import com.joinway.framework.support.security.validator.ISecurityValidator;

@Deprecated
public class SecurityAspect {
	private final static Logger log = LoggerFactory.getLogger(SecurityAspect.class);
	
	protected List<ISecurityValidator> validators;
	
	protected Map<CheckPoint, ISecurityValidator> map = new HashMap<>();
	
	public Object doAround(ProceedingJoinPoint point) throws Throwable {
		
//		if(CollectionUtils.isNotEmpty(validators)){
		Security security = AopHelper.getAnnotation(point, Security.class, true);
		
		if(security != null && ArrayUtils.isNotEmpty(security.value())){
			for(CheckPoint p : security.value()){
				ISecurityValidator validator = map.get(p);
				
				if(validator != null){
					validator.validate(point);
				}
			}
			
//			for(SecurityValidator validator : validators){
//				if(isTarget(security.value(), validator.getTargetCheckPoint())){
//					validator.validate(point);
//				}
//			}
		}
//		}
		
		return point.proceed();
	}
	
//	boolean isTarget(SecurityCheckPoint[] points, SecurityCheckPoint target){
//		boolean found = false;
//		
//		for(SecurityCheckPoint p : points){
//			if(p == target){
//				found = true;
//				break;
//			}
//		}
//		
//		return found;
//	}

	public List<ISecurityValidator> getValidators() {
		return validators;
	}

	public void setValidators(List<ISecurityValidator> validators) {
		this.validators = validators;
		
		if(CollectionUtils.isNotEmpty(validators)){
			validators.stream().forEach(v -> map.put(v.getCheckPoint(), v));
		}
	}
}
